﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;

namespace Catering
{
    public static class Toolss
    {
        /// <summary>
        /// 添加SQL查询条件
        /// </summary>
        /// <param name="StrWhere">现有sql条件</param>
        /// <param name="AddWhere">需添加的Where条件</param>
        public static string AddSQLWhere(string StrWhere, string AddWhere)
        {
            if (StrWhere.Length > 0)
            {
                AddWhere = " and " + AddWhere;
            }
            return AddWhere;
        }

        //公用的DropDownList绑定方法
        public static void LoadDrop(this DropDownList drop, DataTable dt, string strValue, string strText, bool IsAddNul = false)
        {
            drop.Items.Clear();
            if (IsAddNul)
            {
                ListItem ite = new ListItem();
                ite.Text = "全部";
                ite.Value = "-10";
                drop.Items.Add(ite);
            }

            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListItem item = new ListItem();
                    item.Text = dt.Rows[i][strText].ToString();
                    item.Value = dt.Rows[i][strValue].ToString();
                    drop.Items.Add(item);
                }
            }
        }

        public static void LoadDrop_DishTypes(this DropDownList drop,int id)
        {
            drop.Items.Clear();
            DataTable dt = new Catering_Rules.DishTypes().GetList("DTID=" + id).Tables[0];
            int j = 0;
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListItem item = new ListItem();
                    item.Text = dt.Rows[i]["DTName"].ToString();
                    item.Value =  dt.Rows[i]["id"].ToString();
                    drop.Items.Add(item);
                    j++;
                }
                dt.Dispose();
            }
            dt = new Catering_Rules.DishType().GetList("ParentID=" + id).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListItem item = new ListItem();
                    item.Text = dt.Rows[i]["DT"].ToString();
                    item.Value = dt.Rows[i]["id"].ToString() + "-";
                    drop.Items.Add(item);
                    j++;
                }
                dt.Dispose();
            }
        }

        //公用的RadioButtonList绑定方法
        public static void LoadRad(this RadioButtonList Rad, DataTable dt, string strValue, string strText)
        {
            Rad.Items.Clear();
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListItem item = new ListItem();
                    item.Text = dt.Rows[i][strText].ToString();
                    item.Value = dt.Rows[i][strValue].ToString();
                    Rad.Items.Add(item);
                }
            }
        }

        //根据DT获取对应的option项
        public static string GetOption(this DataTable dt, string strValue, string strText, bool IsAddNul = false)
        {
            StringBuilder sb = new StringBuilder();
            if (IsAddNul)
            {
                sb.Append("<option value=\"-1\">请选择</option>");
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    sb.Append("<option value=\"" + row[strValue].ToString() + "\">" + row[strText].ToString() + "</option>");
                }
            }
            return sb.ToString();
        }

        //MD5加密
        public static string GetMD5(this string sDataIn, string move)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider
            md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bytValue, bytHash;
            bytValue = System.Text.Encoding.UTF8.GetBytes(move + sDataIn);
            bytHash = md5.ComputeHash(bytValue);
            md5.Clear();
            string sTemp = "";
            for (int i = 0; i < bytHash.Length; i++)
            {
                sTemp += bytHash[i].ToString("x").PadLeft(2, '0');
            }
            return sTemp;
        }

        //验证是否具有该权限
        /// <param name="strurl">页面地址(如：index.aspx)</param>
        /// <param name="strName">功能名称(如：新增、删除)</param>
        /// <returns></returns>
        public static bool IsVerification(string RoleID, string strurl, string stroperatingName)
        {
            Catering_Model.Role temprow = new Catering_Rules.Role().GetModel(Convert.ToInt32(RoleID));
            if (temprow != null && temprow.temp1 == 10) return true;

            string ModuleID = "";//模块ID
            string operating = "";//功能ID

            DataTable dt_Module = new Catering_Rules.Module().GetList("PageUrl='" + strurl + "'").Tables[0];
            if (dt_Module != null && dt_Module.Rows.Count > 0)
            {
                ModuleID = dt_Module.Rows[0]["id"].ToString();
                if (stroperatingName != "-1")
                {
                    DataTable dt_operating = new Catering_Rules.Module_operating().GetList("ModuleID=" + ModuleID + " and operating='" + stroperatingName + "'").Tables[0];
                    if (dt_operating != null && dt_operating.Rows.Count > 0)
                    {
                        operating = dt_operating.Rows[0]["id"].ToString();
                    }
                }
                else
                {
                    operating = "-1";
                }
            }

            if (ModuleID == "" || operating == "")
            {
                return false;
            }
            else
            {
                string strwhere = "RoleID=" + RoleID + " and ModuleID=" + ModuleID + " and OperatingID=" + operating;
                DataTable dt_Role_Module = new Catering_Rules.Role_Module().GetList(strwhere).Tables[0];
                return (dt_Role_Module != null && dt_Role_Module.Rows.Count > 0);
            }

        }

        //根据条件获取单个字段值
        /// <param name="strTableName">表名</param>
        /// <param name="strColumName">需要查询的字段名称</param>
        /// <param name="strWhere">条件</param>
        /// <returns></returns>
        public static object GetSingle(string strTableName, string strColumName, string strWhere = null)
        {
            string strSql = string.Empty;
            if (strWhere == null)
            {
                strSql = "select " + strColumName + " from " + strTableName;
            }
            else
            {
                strSql = "select " + strColumName + " from " + strTableName + " where " + strWhere;
            }
            return Catering_DBOpertion.DbHelperSQL.GetSingle(strSql);
        }

        ///// <summary>
        ///// 根据条件获取库存信息
        ///// </summary>
        ///// <param name="ClassID">班组ID</param>
        ///// <param name="RawID">班组ID</param>
        ///// <returns>顺序：ID、结余量、单价</returns>
        //public static ArrayList GetKCinfo(string ClassID, string RawID)
        //{
        //    ArrayList al = new ArrayList();
        //    string strwhere = "ClassID= " + ClassID + "and RAWID= " + RawID;
        //    DataTable dt_InDbInfo = new Catering_Rules.InDbInfo().GetList(1, strwhere, "IntDate desc").Tables[0];
        //    if (dt_InDbInfo != null && dt_InDbInfo.Rows.Count > 0)
        //    {
        //        int id = Convert.ToInt32(dt_InDbInfo.Rows[0]["id"].ToString());//数据编号
        //        decimal NumCount = Convert.ToDecimal(dt_InDbInfo.Rows[0]["temp1"].ToString());//结余量
        //        decimal danjia = Convert.ToDecimal(dt_InDbInfo.Rows[0]["temp2"].ToString());//平均单价
        //        al.Add(id);
        //        al.Add(NumCount);
        //        al.Add(danjia);
        //    }
        //    return al;
        //}

        //根据条件获取规格字符串
        /// <param name="RawID">原料ID</param>
        /// <returns>规格字符串</returns>
        public static string GetGuiGeByRawID(string RawID)
        {
            string str_guige = string.Empty;
            DataTable dt_RawMaterial_Unit = new Catering_Rules.RawMaterial_Unit().GetList("RawMaterialID=" + RawID).Tables[0];
            if (dt_RawMaterial_Unit != null && dt_RawMaterial_Unit.Rows.Count > 0)
            {
                foreach (DataRow row in dt_RawMaterial_Unit.Rows)
                {
                    if (row["Number"].ToString() != "")
                    {
                        str_guige += row["Number"].ToString() + new Catering_Rules.Units().GetModel(Convert.ToInt32(row["UnitID"].ToString())).UName + "|";
                    }
                }
            }
            return str_guige;
        }

        //绑定星期对应的日期
        public static string GetWeekStr(this DayOfWeek date)
        {
            switch (date)
            {
                case DayOfWeek.Friday:
                    return "星期五";
                    break;
                case DayOfWeek.Monday:
                    return "星期一";
                    break;
                case DayOfWeek.Saturday:
                    return "星期六";
                    break;
                case DayOfWeek.Sunday:
                    return "星期日";
                    break;
                case DayOfWeek.Thursday:
                    return "星期四";
                    break;
                case DayOfWeek.Tuesday:
                    return "星期二";
                    break;
                case DayOfWeek.Wednesday:
                    return "星期三";
                    break;
            }
            return "";
        }

        //修改字符串
        public static string SetToString(this string str)
        {
            return str == "" ? "0" : str;
        }

        //单位换算
        public static decimal GetUnitConversion(string RawID)
        {
            Catering_Model.E_RawMaterial md_RawMaterial = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(RawID));
            int UnitID = Convert.ToInt32(md_RawMaterial.temp2);//入库单位ID
            int gUnid = 1;//固定值，g的单位ID为1（其实应该做成配置）
            DataTable dt_RawMaterial_Unit_g = new Catering_Rules.RawMaterial_Unit().GetList("RawMaterialID=" + RawID + " and UnitID=" + gUnid + " and CONVERT(float,Number)>0").Tables[0];
            DataTable dt_RawMaterial_Unit_In = new Catering_Rules.RawMaterial_Unit().GetList("RawMaterialID=" + RawID + " and UnitID=" + UnitID + " and CONVERT(float,Number)>0").Tables[0];
            bool b_g = (dt_RawMaterial_Unit_g != null && dt_RawMaterial_Unit_g.Rows.Count > 0);
            bool b_In = (dt_RawMaterial_Unit_In != null && dt_RawMaterial_Unit_In.Rows.Count > 0);
            if (b_g && b_In)
            {
                decimal d_g = Convert.ToDecimal(dt_RawMaterial_Unit_g.Rows[0]["Number"].ToString());
                decimal d_In = Convert.ToDecimal(dt_RawMaterial_Unit_In.Rows[0]["Number"].ToString());
                return d_In / d_g;
            }
            else
            {
                //按照入库单位为KG，并且按照1:1000的比例进行换算
                return 1 / 1000;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="StartTime">需转换的开始时间</param>
        /// <param name="EndTime">需转换的结束时间</param>
        /// <param name="TimeType">时间类型：YEAR or MONTH</param>
        /// <param name="StartDay">转换后的起始日期，如果为0则为自然月起始日期</param>
        /// <param name="EndDay">转换后的结束日期，如果为0则为自然月结束日期</param>
        /// <param name="IsHavePreDays">是否包含上一月的日期（即日期是否从上个月算起）</param>
        /// <param name="IsAcrossYear">是否跨年:true:是，false:否</param>
        /// <param name="OutStartTime">转换后返回的开始时间</param>
        /// <param name="OutEndTime">转换后返回的结束时间</param>
        public static void GetFormatDateTime(DateTime StartTime, DateTime EndTime, String TimeType, int StartDay, int EndDay, bool IsHavePreDays, bool IsAcrossYear, out DateTime OutStartTime, out DateTime OutEndTime)
        {
            OutStartTime = StartTime;
            OutEndTime = EndTime;

            if (StartDay != 0 && EndDay != 0)
            {
                if (IsAcrossYear)
                {
                    //跨年
                    if (IsHavePreDays)
                    {
                        //包含上一月的日期
                        if (TimeType == "YEAR")
                        {
                            OutStartTime = DateTime.Parse((StartTime.Year - 1) + "-12-" + StartDay);
                            OutEndTime = DateTime.Parse(EndTime.Year + "-12-" + EndDay).AddDays(1).AddSeconds(-1);
                        }
                        else if (TimeType == "MONTH")
                        {
                            OutStartTime = DateTime.Parse(StartTime.Year + "-" + StartTime.Month + "-" + StartDay).AddMonths(-1);
                            OutEndTime = DateTime.Parse(EndTime.Year + "-" + EndTime.Month + "-" + EndDay).AddDays(1).AddSeconds(-1);
                        }
                    }
                    else
                    {
                        //不包含上一月的日期
                        if (TimeType == "YEAR")
                        {
                            OutStartTime = DateTime.Parse(StartTime.Year + "-12-" + StartDay);
                            OutEndTime = DateTime.Parse((EndTime.Year + 1) + "-12-" + EndDay).AddDays(1).AddSeconds(-1);
                        }
                        else if (TimeType == "MONTH")
                        {
                            OutStartTime = DateTime.Parse(StartTime.Year + "-" + StartTime.Month + "-" + StartDay);
                            OutEndTime = DateTime.Parse(EndTime.Year + "-" + EndTime.Year + "-" + EndDay).AddMonths(1).AddDays(1).AddSeconds(-1);
                        }
                    }
                }
                else
                {
                    //不跨年
                    if (TimeType == "YEAR")
                    {
                        if (IsHavePreDays)
                        {
                            OutStartTime = DateTime.Parse(StartTime.Year + "-01-01");
                            OutEndTime = DateTime.Parse(EndTime.Year + "-12-" + EndDay).AddDays(1).AddSeconds(-1);
                        }
                        else
                        {
                            OutStartTime = DateTime.Parse(StartTime.Year + "-12-" + StartDay);
                            OutEndTime = DateTime.Parse(EndTime.Year + "-12-" + EndDay).AddDays(1).AddSeconds(-1);
                        }

                    }
                }
            }


        }

        //获取原料规格
        /// <summary>
        /// 
        /// </summary>
        /// <param name="RawID"></param>
        /// <param name="UtilName"></param>
        /// <param name="iskg">计算单位是kg还是g</param>
        /// <returns></returns>
        public static decimal GetSpecifications(int RawID, string UnitName, out bool iskg)
        {
            decimal UtilKg = 1;
            bool flag = false;
            bool isl = false;
            bool isml = false;
            iskg = true;
            if (UnitName == "kg")
            {
                return 1;
            }
            else if (UnitName == "g")
            {
                iskg = false;
                return 1;
            }
            else if (UnitName == "升")
            {
                UtilKg = UtilKg * 920;
                iskg = false;
                return UtilKg;
            }
            else if (UnitName == "毫升")
            {
                UtilKg = UtilKg * decimal.Parse("0.92");
                iskg = false;
                return UtilKg;
            }

            DataTable dt_RawUnit = new Catering_Rules.RawMaterial_Unit().GetList("RawMaterialID=" + RawID).Tables[0];
            if (dt_RawUnit != null && dt_RawUnit.Rows.Count > 0)
            {
                foreach (DataRow dr in dt_RawUnit.Rows)
                {
                    string number = dr["Number"].ToString();
                    if (dr["Number"] is DBNull || dr["Number"].ToString() == "") continue;

                    if (!string.IsNullOrEmpty(number))
                    {
                        Catering_Model.Units md_unti = new Catering_Rules.Units().GetModel(Convert.ToInt32(dr["UnitID"]));
                        if (flag)
                        {
                            UtilKg = UtilKg * Convert.ToDecimal(number);
                        }
                        if (!flag && md_unti.UName == UnitName) flag = true;

                        if (flag && md_unti.UName == "kg")
                        {
                            flag = false;
                            iskg = true;
                        }
                        else if (flag && md_unti.UName == "g")
                        {
                            flag = false;
                            iskg = false;
                        }
                        else if (flag && md_unti.UName == "升")
                        {
                            isl = true;
                            flag = false;
                        }
                        else if (flag && md_unti.UName == "毫升")
                        {
                            isml = true;
                            flag = false;
                        }
                    }
                }
                if (isl)
                {
                    UtilKg = UtilKg * 920;
                    iskg = false;
                }
                else if (isml)
                {
                    UtilKg = UtilKg * decimal.Parse("0.92");
                    iskg = false;
                }
                if (flag)
                {
                    iskg = false;
                    UtilKg = 1;
                }
            }
            return UtilKg;
        }

        #region cookie操作

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        public static void WriteCookie(string strName, string strValue)
        {
            WriteCookie(strName, strValue, "", "");
        }

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="domain">域</param>
        /// <param name="path">路径</param>
        public static void WriteCookie(string strName, string strValue, string domain, string path)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            if (!string.IsNullOrEmpty(path)) cookie.Path = path;
            if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain;
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="strValue">过期时间(分钟)</param>
        public static void WriteCookie(string strName, string strValue, int expires)
        {
            WriteCookie(strName, strValue, expires, "", "/");
        }

        /// <summary>
        /// /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="expires">过期时间(分钟)</param>
        /// <param name="domain">域</param>
        /// <param name="path">路径</param>
        public static void WriteCookie(string strName, string strValue, int expires, string domain, string path)
        {
            HttpCookie cookie = HttpContext.Current.Response.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            cookie.Expires = DateTime.Now.AddMinutes(expires);
            if (!string.IsNullOrEmpty(path)) cookie.Path = path;
            if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain;
            HttpContext.Current.Response.AppendCookie(cookie);

        }

        /// <summary>
        /// 读cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <returns>cookie值</returns>
        public static string GetCookie(string strName)
        {
            try
            {
                if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
                {
                    return HttpContext.Current.Request.Cookies[strName].Value.ToString();
                }
            }
            catch
            {
            }

            return "";
        }

        /// <summary>
        /// 数字处理
        /// </summary>
        /// <param name="old">要处理的数字</param>
        /// <param name="No">保留小数点位数</param>
        /// <param name="type">1：全部舍入、2：全部进1、3：四舍五入</param>
        /// <returns></returns>
        public static decimal GetMathResult(decimal old, int No, int type)
        {
            decimal tempNum = 1;
            if (type == 3) return GetRound(old, No);
            if (No > 0) tempNum = Convert.ToInt32(Math.Pow(10, No));
            old = old * tempNum;
            old = Math.Truncate(old);
            old = old / tempNum;
            if (type == 1) return old;
            return old + 1 / tempNum;
        }

        public static string GetResult(int x, int y)
        {
            int temp=GetMaxGongyueShu(x, y);
            return (x / temp) + ":" + (y / temp);
        }

        public static int GetMaxGongyueShu(int x, int y)
        {
            int temp;
            if (x < y)
            { temp = x; x = y; y = temp; }
            while (y != 0)
            { temp = x % y; x = y; y = temp; } return (x);
        }

        /// <summary>
        /// 四舍五入
        /// </summary>
        /// <param name="dblnum"></param>
        /// <param name="numberprecision"></param>
        /// <returns></returns>
        private static decimal GetRound(decimal dblnum, int numberprecision)
        {
            int tmpNum = dblnum > 0 ? 5 : -5;
            decimal dblreturn = Math.Truncate(dblnum * Convert.ToDecimal(Math.Pow(10, numberprecision + 1))) + tmpNum;
            dblreturn = Math.Truncate(dblreturn / 10) / Convert.ToDecimal(Math.Pow(10, numberprecision));
            return dblreturn;
        }

        #endregion


        #region 文件操作

        /// <summary>
        /// 返回文件是否存在
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否存在</returns>
        public static bool FileExists(string filename)
        {
            bool result = false;
            try
            {
                result = System.IO.File.Exists(filename);
            }
            catch
            {
            }
            return result;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool DeleteFile(string filename)
        {
            if (FileExists(GetMapPath(@"" + filename)))
            {
                File.Delete(GetMapPath(@"" + filename));
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }

        #endregion

        #region Excel资源回收

        //[DllImport("User32.dll", CharSet = CharSet.Auto)]
        //public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        //public static void KillExcel(Microsoft.Office.Interop.Excel.Application excel)
        //{
        //    IntPtr t = new IntPtr(excel.Hwnd); //得到这个句柄，具体作用是得到这块内存入口 
        //    int k = 0;
        //    GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
        //    System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
        //    p.Kill(); //关闭进程k
        //}

        [DllImport("user32.dll", SetLastError = true)]

        static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
        public static void KillExcel(Microsoft.Office.Interop.Excel.Application m_objExcel)
        {
            try
            {
                if (m_objExcel != null)
                {
                    int lpdwProcessId;
                    GetWindowThreadProcessId(new IntPtr(m_objExcel.Hwnd), out lpdwProcessId); System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
                }
            }
            catch { }
        }

        #endregion


    }
}